from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_, and_
from datetime import datetime
from database import get_db
from models.logs import RequestLog
from utils.token_utils import get_current_user

router = APIRouter(
    prefix="/api/logs/v1",
    tags=["日志管理模块"],
    responses={404: {"description": "Not found"}}
)


@router.get("/", summary="查询日志", response_model=dict)
def cat_logs(
        db: Session = Depends(get_db),
        _=Depends(get_current_user),
        page: int = Query(1, ge=1, description="当前页码，从1开始"),
        page_size: int = Query(20, ge=1, le=100, description="每页数量，最大100条"),
        keyword: str = Query(None, description="模糊搜索：URL 或 用户名"),
        method: str = Query(None, description="请求方法过滤，如 GET / POST"),
        start_time: datetime = Query(None, description="起始时间（格式: YYYY-MM-DDTHH:MM:SS）"),
        end_time: datetime = Query(None, description="结束时间（格式: YYYY-MM-DDTHH:MM:SS）")
):
    # 构造筛选条件
    filters = []

    if keyword:
        filters.append(or_(
            RequestLog.url.like(f"%{keyword}%"),
            RequestLog.username.like(f"%{keyword}%")
        ))

    if method:
        filters.append(RequestLog.method == method.upper())

    if start_time and end_time:
        filters.append(and_(
            RequestLog.request_time >= start_time,
            RequestLog.request_time <= end_time
        ))
    elif start_time:
        filters.append(RequestLog.request_time >= start_time)
    elif end_time:
        filters.append(RequestLog.request_time <= end_time)

    # 查询总数
    base_query = db.query(RequestLog).filter(*filters)
    total = base_query.count()

    # 分页换算 offset
    offset = (page - 1) * page_size

    logs = (
        base_query.order_by(RequestLog.id.desc())
        .offset(offset)
        .limit(page_size)
        .all()
    )

    result = []
    for log in logs:
        if "login" in log.url or "register" in log.url:
            response_body = None
            request_body = None

        else:
            response_body = log.response_body
            request_body = log.request_body

        result.append({
            "id": log.id,
            "username": log.username,
            "url": log.url,
            "method": log.method,
            "request_body": request_body,
            "response_body": response_body,
            "status_code": log.status_code,
            "client_ip": log.client_ip,
            "request_time": log.request_time
        })

    return {
        "code": 200,
        "message": "日志查询成功",
        "data": result,
        "pagination": {
            "page": page,
            "page_size": page_size,
            "total": total,
            "total_page": (total + page_size - 1) // page_size
        }
    }
